<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins" class="view-table">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" v-if="formshow">
          <template #SpuCategory>
            <SelectProductCategories filterable multiple collapse-tags slotType="cascader" style="width: 200px" v-model:modelValue="form['spu_category']" placeholder="产品分类" />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <el-button type="primary" @click="EstimatedSalesRef.open()">系统预估销量设置</el-button>

        <el-button class="ml-auto" @click="openConfirmInput('dropdown')"> 历史数据导出功能 </el-button>

        <el-button @click="importHandleClick">
          <span class="flex items-center"> <svg-icon icon-class="import" class="mr-[4px]" /> 导出 </span>
        </el-button>
      </template>

      <template #soltHeaderTransit="{ column }">
        <div class="flex items-center" v-for="item in transitHeader" :key="item.title">
          <div>{{ item.title }}</div>
          <div class="ml-[8px]"></div>
        </div>
      </template>
      <template #soltHeader="{ column }">
        <div class="flex items-center">
          <div class="mr-[8px]">{{ column.title }}</div>

          <el-dropdown trigger="click">
            <span class="el-dropdown-link text-[#3487ff]">
              排序
              <div class="dk-iconfont icon-ArrowDown"></div>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <!-- asc：升序；desc：降序 -->
                <div class="flex items-center px-[4px] py-[8px]" v-for="item in headerMemu[column.field]" :key="item.title">
                  <div>
                    {{ item.title }}
                  </div>
                  <div class="ml-[8px] flex" style="flex-direction: column">
                    <div
                      style="font-size: 10px !important"
                      class="mb-[-4px] cursor-pointer dk-iconfont icon-CaretTop"
                      :class="item.type == 'asc' ? 'text-[#3487ff]' : 'text-[#999]'"
                      @click="tableSort(item, 'asc')"
                    ></div>

                    <div
                      style="font-size: 10px !important"
                      class="mt-[-2px] cursor-pointer dk-iconfont icon-CaretBottom"
                      :class="item.type == 'desc' ? 'text-[#3487ff]' : 'text-[#999]'"
                      @click="tableSort(item, 'desc')"
                    ></div>

                    <!-- <CaretTop style="width: 1em; height: 1em" class="mb-[-2px] cursor-pointer" :class="item.type == 'asc' ? 'text-[#3487ff]' : 'text-[#999]'" @click="tableSort(item, 'asc')" />
                    <CaretBottom style="width: 1em; height: 1em" class="mt-[-2px] cursor-pointer" :class="item.type == 'desc' ? 'text-[#3487ff]' : 'text-[#999]'" @click="tableSort(item, 'desc')" /> -->
                  </div>
                </div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template>

      <!-- 预估销量 -->
      <template #Sales="{ row }">
        <el-popover placement="left" :width="720" trigger="click" @show="salesQtyShow(row)">
          <!-- title="历史销量" -->
          <div>
            <div class="mb-[4px] flex items-center">
              <div class="text-[16px] w-[200px]">历史销量</div>

              <el-radio-group v-model="salesQtyForm.is_site" @change="salesQtyGetData">
                <el-radio :value="0" :label="0">北京时间</el-radio>
                <el-radio :value="1" :label="1">站点时间 （UTC{{ salesQtyForm.site_time_zone > 0 ? `+${salesQtyForm.site_time_zone}` : salesQtyForm.site_time_zone }}）</el-radio>
              </el-radio-group>
            </div>
            <div class="grid grid-cols-10 day-table">
              <div v-for="item in salesQtyTable" :key="item.day">
                <div class="header">{{ item.day || "-" }}</div>
                <div class="value">{{ item.quantity }}</div>
              </div>
            </div>

            <div class="text-[#E50113] mt-[8px]">说明：当前计算的销量是下单时间的销量；销量显示‘-’，表示当天 “断货”或者 listing状态是“停售”且当天销量为0</div>
          </div>
          <template #reference>
            <div class="bold-text" v-popover="popoverRef" v-click-outside="onClickOutside">预估销量:{{ row.predict_sales_qty }}</div>
          </template>
        </el-popover>

        <VText title="今天销量" :value="row.today_qty" line="1" class="text-green font-bold" />
        <VText title="昨天销量" :value="row.yesterday_qty" line="1" class="text-yellow font-bold" />
        <VText title="前天销量" :value="row.before_yesterday_qty" line="1" class="text-red font-bold" />
        <VText title="上前销量" :value="row.prev_before_yesterday_qty" line="1" class="text-red font-bold" />
      </template>
    </VTable>

    <!-- 系统预估销量设置 -->
    <EstimatedSales ref="EstimatedSalesRef" />

    <VLog ref="logRef" :api="listingLog"></VLog>

    <!-- 采购历史记录 -->
    <PurchaseDtl ref="PurchaseDtlRef" />
    <!-- 头程历史记录 -->
    <HeadProcedureDtl ref="HeadProcedureDtlRef" />
    <!-- 系统可用库存 -->
    <AssembleSkuSee ref="AssembleSkuSeeRef" />

    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>

    <!-- 弹窗 表格数据展示 -->
    <DialogTableInfo v-model="dialogTableInfoVisible" v-bind="tableInfoConfirm" />

    <!-- 弹窗 表单编辑 -->
    <ConfirmInput v-model="batchVisible" v-bind="currentConfirm" @submit="handleConfirmSubmit" @close="handleConfirmClose" />

    <!-- ASIN销量趋势 -->
    <AsinSalesTrend ref="AsinSalesTrendRef" />

    <el-tooltip ref="tipRef" :visible="tip.visible" :virtual-ref="tip.ref" virtual-triggering placement="top" :enterable="false" effect="light">
      <template #content>
        <div>
          <div class="text-[16px] my-[6px]">热卖信息</div>
          <el-table :data="tip.tableData" style="width: 100%">
            <el-table-column prop="date" label="国家" width="180">
              <template #default="{ row }">
                {{ row.country?.map((v) => v.country_name).join() }}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="热卖月份" width="180">
              <template #default="{ row }"> {{ row.hot_sell_start_month }} - {{ row.hot_sell_end_month }} </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </div>
      </template>
    </el-tooltip>
  </VPage>
</template>

<script setup lang="jsx">
import { asinManagementList, asinManagementCreate, asinManagementEdit, asinManagementBatchUpdateField, asinManagementLog } from "@/api/base"
import { enumGet, getCountry, getShopOptions, getPlatformsSites, getGoodsSkuList, amazonSkuDetail } from "@/api"

import { amazonListingList, listingLog, historySalesVolume, historySalesExport, ownerInventory } from "@/api/amazon"
// 采购历史记录
import PurchaseDtl from "./components/purchaseDtl.vue"
const PurchaseDtlRef = ref()

// 头程历史记录
import HeadProcedureDtl from "./components/headProcedureDtl.vue"
const HeadProcedureDtlRef = ref()

// 系统可用库存
import AssembleSkuSee from "./components/assembleSkuSee.vue"
const AssembleSkuSeeRef = ref()
// 系统预估销量设置
import EstimatedSales from "./components/estimatedSales.vue"
const EstimatedSalesRef = ref()

// ASIN销量趋势
import AsinSalesTrend from "./components/AsinSalesTrend/index"
const AsinSalesTrendRef = ref()

const getDate = (day = 1) => {
  let start = new Date()
  start.setTime(start.getTime() - 3600 * 1000 * 24 * day)
  return [new Date(start.setHours(0, 0, 0, 0)), new Date(new Date().setHours(23, 59, 59, 0))].map((v) => parseTime(v, "{y}-{m}-{d}"))
}
// 弹窗 表单编辑
import ConfirmInput from "@/components/ConfirmInput/index.vue"
const batchVisible = ref(false)
const currentConfirm = ref({})
const batchOConfig = {
  dropdown: {
    formOptions: { inline: true, labelPosition: "top" },
    width: 720,
    title: "历史数据导出功能",
    form: {},
    fieldOptions: [
      {
        label: "请选择导出时间范围",
        field: "date",
        type: "dateTimeRangeNorm",
        itemProps: {
          type: "daterange",
          valueFormat: "YYYY-MM-DD",
        },
        style: { width: "300px" },
      },
    ],
  },
}
const openConfirmInput = (type) => {
  // console.log(batchOConfig.base_lt_days)
  let confirm = {}
  switch (type) {
    case "dropdown": // 历史数据导出功能
      confirm = batchOConfig.dropdown
      confirm.form.date = getDate(30)
      break
  }
  confirm.type = type
  console.log("currentConfirm")
  currentConfirm.value = confirm
  batchVisible.value = true
}

const handleConfirmSubmit = (param) => {
  try {
    console.log(param)
    let params = {}
    let requests = null
    let message = ""
    switch (currentConfirm.value.type) {
      case "dropdown": // 历史数据导出功能
        requests = historySalesExport
        params = {}
        let checkRow = tableRef?.value?.$table?.getCheckboxRecords()
        if (checkRow?.length) {
          params.id = checkRow.map((v) => v.id)
        } else {
          params = tableRef?.value.getQueryForm()
          let { skuRange } = tableRef?.value.getForm()
          if (skuRange) {
            params[skuRange.type] = skuRange?.value?.split("\n")?.filter((v) => !!v.trim())
          }
        }
        params.date = param.date
        params.platform_id = 2
        message = "下载成功"
        break
    }

    requests(params).then((res) => {
      if (currentConfirm.value.type == "dropdown") {
        ElMessageBox.confirm("导出成功，是否跳转导出中心下载文件！", { confirmButtonText: "跳转", cancelButtonText: "取消" })
          .then(() => {
            action.setGlobalState({ changeMicoTabsPath: { path: "/user/profile", type: "push" } })
          })
          .catch(() => {})
      }
      ElMessage.success(message || res.message)
      batchVisible.value = false
      nextTick(() => {
        currentConfirm.value = {}
      })
    })
  } catch (error) {}
}
const handleConfirmClose = () => {
  batchVisible.value = false
  nextTick(() => {
    currentConfirm.value = {}
  })
}

// 弹窗 表格数据展示
import DialogTableInfo from "@/components/DialogTableInfo/index.vue"
// 弹窗 表格数据展示
const dialogTableInfoVisible = ref(false)
const tableInfoConfirm = ref({})
const dialogTabelInfoConfig = {
  inventory: {
    title: "本地仓库存",
    api: ownerInventory,
    tableOptions: {
      // border: false,
      height: "500",
      columns: [
        { field: "warehouse_name", title: "仓库名称" },
        { field: "wms_attribute_cn", title: "仓库属性", width: "100" },
        { field: "asin", title: "ASIN", width: "120" },
        { field: "owner_name", title: "货主", width: "180" },
        { field: "num", title: "可用库存", width: "90" },
        { field: "lock_num", title: "锁定库存", width: "90" },
        // { field: "transit_num", title: "在途库存", width: "90" },
      ],
    },
  },
}
const openTableInfo = async (e, params) => {
  console.log(e)
  switch (e) {
    case "inventory":
      tableInfoConfirm.value = dialogTabelInfoConfig.inventory
      let res = await tableInfoConfirm.value.api({ data: [{ sku: params.sku }] })
      let data = res.data?.[0]?.inventory
      tableInfoConfirm.value.tableOptions.data = data.filter((v) => "1,5".includes(v.wms_attribute))
      break
    default:
      break
  }
  dialogTableInfoVisible.value = true
}

const transitHeader = reactive([
  { title: "采购中", key: "purchase_processing_num", type: "" },
  { title: "本地仓库存", key: "xxxxxxx", type: "" },
  // { title: "FBA在途", key: "transit_count", type: "" },
])

const headerMemu = reactive({
  sales: [
    { title: "预估销量", key: "predict_sales_qty", type: "" },
    { title: "今天销量", key: "today_qty", type: "" },
    { title: "昨天销量", key: "yesterday_qty", type: "" },
    { title: "前天销量", key: "before_yesterday_qty", type: "" },
    { title: "上前销量", key: "prev_before_yesterday_qty", type: "" },
  ],
  qty: [
    { title: "一周销量", key: "one_week_qty", type: "" },
    { title: "两周销量", key: "tow_week_qty", type: "" },
    { title: "30天销量", key: "thirty_day_qty", type: "" },
    { title: "90天销量", key: "ninety_day_qty", type: "" },
  ],
  inventory: [
    { title: "库存合计", key: "inventory_total", type: "" },
    { title: "FBA可用库存", key: "inventory_num", type: "" },
    { title: "FBA锁定库存", key: "inventory_lock_num", type: "" },
    { title: "不可售", key: "inventory_unsale_num", type: "" },
    { title: "售完天数", key: "predict_sales_day", type: "" },
  ],
  time: [
    { title: "创建时间", key: "create_time", type: "" },
    { title: "上架时间", key: "platform_date", type: "" },
    { title: "更新时间", key: "update_time", type: "" },
    { title: "首次到达FBA时间", key: "receipt_goods_time", type: "" },
  ],
})

const tableSort = (item, value) => {
  let type = item.type == value ? "" : value
  for (const key in headerMemu) {
    headerMemu[key].forEach((item) => {
      item.type = ""
    })
  }
  // item.type = item.type == value ? "" : value
  item.type = type
  tableRef?.value.setFormField("isSort", true)
  query()
}
import action from "@/utils/action.js"

// 预估销量
import { ClickOutside as vClickOutside } from "element-plus"
const popoverRef = ref()
const onClickOutside = () => {
  // console.log(12)
  // unref(popoverRef).popperRef?.delayHide?.()
}

import { parseTime } from "@/utils/ruoyi"
const salesQtyForm = ref({ is_site: 0 })
const salesQtyTable = ref([])
const salesQtyShow = async (row) => {
  let datetime = getDate(29)
  let params = {
    sku: row.sku,
    platform_sku: row.platform_sku,
    asin: row.asin,
    shop_id: row.shop_id,
    payment_date_start: datetime[0],
    payment_date_end: datetime[1],
    platform_id: row.platform_id,
    is_site: 0,

    site_time_zone: row.site_time_zone,
  }
  salesQtyForm.value = params
  salesQtyGetData()
}
const salesQtyGetData = async () => {
  const res = await historySalesVolume(salesQtyForm.value)
  res.data.forEach((item) => {
    let day = getDayOfWeek(item.payment_date)
    item.day = `${item.payment_date?.slice(5)} (${day})`
  })
  res.data = res.data.reverse()
  salesQtyTable.value = res.data
}

const getDayOfWeek = (date) => {
  const days = ["日", "一", "二", "三", "四", "五", "六"]
  const dayNumber = new Date(date).getDay()
  return days[dayNumber]
}

// console.log(getDayOfWeek()) // 输出例如 "星期三"

import { ElMessage, ElMessageBox } from "element-plus"
import { onMounted, ref, toRefs } from "vue"

import XForm from "@/components/XForm/index.vue"
import SelectProductCategories from "./components/ProductCategories/index.vue"

import VLog from "@/components/VLog"
const logRef = ref()

const tipRef = ref()

const tip = ref({
  visible: false,
  tableData: [],
  ref: null,
  time: null,
})

const mouseleave = () => {
  setTimeout(() => {
    tip.value = {
      visible: false,
      tableData: [],
      ref: null,
      time: null,
    }
  }, 400)
}
const mouseenter = ({ target }, row) => {
  clearTimeout(tip.value.time)
  tip.value.time = setTimeout(() => {
    tip.value = {
      visible: true,
      tableData: row.goods_sku_sell_month,
      ref: target,
      time: null,
    }
  }, 300)
}

import DerivedCenter from "@/components/DerivedCenter"

// 导出中心
const DerivedCenterRef = ref()
const importHandleClick = async () => {
  let condition = {}
  let checkRow = tableRef?.value?.$table?.getCheckboxRecords()
  if (checkRow?.length) {
    condition.id = checkRow.map((v) => v.id)
  } else {
    condition = tableRef?.value.getQueryForm()
    let { skuRange, asinRange } = tableRef?.value.getForm()
    if (skuRange) {
      condition[skuRange.type] = skuRange?.value?.split("\n")?.filter((v) => !!v.trim())
    }
    if (asinRange) {
      condition[asinRange.type] = asinRange?.value?.split("\n")?.filter((v) => !!v.trim())
    }
  }
  condition.platform_id = 2
  let parmas = {
    module: "listing_list_export",
    tag_name: "listing_list_export",
    exportName: "亚马逊刊登listing导出",
    condition,
  }
  DerivedCenterRef.value.open(parmas)
}

const downloadUrl = ref("")

const tableRef = ref()

// 获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  const arr = []
  getCheckboxRecords.map((e) => {
    arr.push(e.id)
  })
  return arr
}

// 查询
const query = () => {
  tableRef?.value.query()
}
// 枚举 数据
const originOption = ref({})

const formshow = ref(false)
//获取下拉数据
onMounted(() => {
  getOption()
})

import { apiGetPlatformSites, getShop } from "@/api/amazon"
const getOption = async () => {
  const { data } = (await apiGetPlatformSites({ platform_ids: [2] })) || {}
  originOption.value.sitesOpt = data.map((n) => ({
    label: n.site_abbrev,
    // value: n.site_id,
    value: n.site_code,
  }))

  const shopRes = await getShop({ platform_ids: [2] })
  originOption.value.shopOpt = shopRes.data.map((n) => ({
    label: n.shop_name,
    value: n.shop_id,
  }))
  formshow.value = true
}

const formOption = ref({
  inline: true,
})

import {
  fieldList, // 搜索条件 配置
} from "./config.jsx"

// 列表配置
const tableOptins = reactive({
  formConfig: {
    save: "publish/amazon/list", // 必填，唯一
    data: {
      isSort: false,
      activity_status: "",
      site_id: "",
      status: "",
      is_requires_stocking: "",
      skuRange: { type: "sku", value: "" },
      asinRange: { type: "asin", value: "" },
      userRange: { type: "operator_user", value: "" },
      timeRange: { type: "create_time", value: [] },
    },
  },

  rowConfig: { height: "142" },
  showOverflow: false,
  columns: [
    { type: "checkbox", fixed: "left", width: 40 },
    { field: "id", title: "草稿编号", width: 80 },
    {
      title: "产品信息",
      width: 300,
      slots: {
        default: ({ row }) => (
          <div class="flex items-center">
            <div class="w-[100px] h-[100px]">
              <el-image style="width:100px;height:100px" src={row.attr_img || ""} />
            </div>

            <div class="ml-[4px] flex-1 " style="width: calc(100% - 104px)">
              <div class="flex items-center">
                <div class="flex mr-[4px]">
                  <div class={`${row.platform_listing_status == "Active" ? "base-tag-primary" : "base-tag-danger"}`}>{row.is_sales_desc}</div>
                  <el-tooltip content="渠道SKU与系统SKU关系" placement="top">
                    <div class={`ml-[4px] cursor-pointer ${row.status == 1 ? "base-tag-danger" : "base-tag-primary"}`}>{row.status == 1 ? "禁用" : "启用"}</div>
                  </el-tooltip>
                </div>
                <div>
                  <VText title="SKU" value={row.sku} line={1} copy />
                </div>
              </div>

              <VText title="渠道SKU" value={row.platform_sku} line={1} copy />
              <VText title="Asin" value={row.asin} line={1} type="link" onClick={() => window.open(row.asin_url, "_blank")} copy />
              <VText title="FNSKU" value={row.fn_sku} line={1} copy />
              <VText title="分类" value={row.spu_category_text} line={1} />

              {row.is_seasonal_product ? (
                <div class="goods-tag" onMouseenter={($event) => mouseenter($event, row)} onMouseleave={mouseleave}>
                  季节产品
                </div>
              ) : (
                ""
              )}
            </div>
          </div>
        ),
      },
    },
    // goods_sku_sell_month

    {
      width: 240,
      field: "sku_cn_title",
      line: 3,
      slots: {
        header: ({}) => (
          <div>
            <div class="text-[var(--base-sub-text-color)]">产品名称</div>
            <div>平台产品标题</div>
          </div>
        ),
        default: ({ row }) => (
          <div>
            <VText value={row.sku_cn_title} line={2} class="text-[var(--base-sub-text-color)]" copy />
            <VText value={row.platform_title} line={2} copy />
          </div>
        ),
      },
    },
    {
      title: "账号/站点/销售",
      width: 240,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center">
              <svg-icon icon-class={`zhandian_${row.site.toLowerCase()}`} class={`zhandian-icon ${row.site.toLowerCase()}`} />
              <VText value={row.site} line={1} />
            </div>

            <VText title="账号" value={row.shop_name} line={1} copy />

            <VText title="销售人员" value={row.operations_personnel} line={1} />
            <VText title="开发人员" value={row.develop_id_text} line={1} />
            <VText title="销售部门" value={row.operations_department} line={1} />
          </div>
        ),
      },
    },
    {
      width: 160,
      slots: {
        header: "soltHeaderTransit",
        default: ({ row }) => (
          <div>
            <div class="flex items-center  text-[16px] text-[#3487ff] cursor-pointer" onClick={() => PurchaseDtlRef.value.open(row)}>
              {row.purchase_processing_num}
              <span class="text-[12px] ml-[6px]">采购记录</span>
              <svg-icon icon-class="baobiao" class="text-[18px]" />
            </div>
            <VText value={"¥" + (row.purchase_processing_amount_price || 0)} line={1} />

            <div class="flex items-center  text-[18px] text-[#3487ff] cursor-pointer mt-[4px]" onClick={() => openTableInfo("inventory", row)}>
              {row.local_inventory_num}
              <span class="text-[12px] ml-[6px]">本地仓库存</span>
              <svg-icon icon-class="baobiao" class=" text-[18px]" />
            </div>
            <VText value={"¥" + (row.local_inventory_amount || 0)} line={1} />
          </div>
        ),
      },
    },
    {
      width: 160,
      title: "待发货件 FBA在途",
      slots: {
        header: ({}) => (
          <div>
            <div>待发货件</div>
            <div>FBA在途</div>
          </div>
        ),

        default: ({ row }) => (
          <div>
            <div class="flex items-center  text-[18px] text-[#3487ff] cursor-pointer mt-[4px]" onClick={() => HeadProcedureDtlRef.value.open("wait", row)}>
              {row.wait_ship_count}
              <span class="text-[12px] ml-[6px]">待发货明细</span>
              <svg-icon icon-class="baobiao" class=" text-[18px]" />
            </div>
            <VText value={"¥" + (row.wait_ship_amount || 0)} line={1} />

            <div class="flex items-center  text-[18px] text-[#3487ff] cursor-pointer mt-[4px]" onClick={() => HeadProcedureDtlRef.value.open("route", row)}>
              {row.transit_count}
              <span class="text-[12px] ml-[6px]">头程记录</span>
              <svg-icon icon-class="baobiao" class=" text-[18px]" />
            </div>
            <VText value={"¥" + (row.transit_purchase_amount || 0)} line={1} />
          </div>
        ),
      },
    },

    {
      title: "近期销量",
      width: 140,
      field: "sales",
      slots: {
        default: "Sales",
        header: "soltHeader",
      },
    },
    {
      title: "销量统计",
      width: 150,
      field: "qty",
      slots: {
        header: "soltHeader",
        default: ({ row }) => (
          <div>
            <VText title="一周" value={row.one_week_qty} line={1} class="text-green font-bold" />
            <VText title="两周" value={row.tow_week_qty} line={1} class="text-yellow font-bold" />
            <VText title="30天" value={row.thirty_day_qty} line={1} class="text-red font-bold" />
            <VText title="90天" value={row.ninety_day_qty} line={1} class="text-red font-bold" />
          </div>
        ),
      },
    },

    {
      title: "FBA库存统计",
      width: 170,
      field: "inventory",
      slots: {
        header: "soltHeader",
        default: ({ row }) => (
          <div>
            <VText title="库存合计" value={row.inventory_total} line={1} class="text-red font-bold" />
            <VText title="FBA可用库存" value={row.inventory_num} line={1} class="text-red font-bold" />
            <VText title="FBA锁定库存" value={row.inventory_lock_num} line={1} class="font-bold" />
            <VText title="不可售数量" value={row.inventory_unsale_num} line={1} />
            <VText title="预计售完天数" value={row.predict_sales_day} line={1} />
          </div>
        ),
      },
    },

    {
      title: "销量对比",
      width: 100,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center">
              <span class="text-[var(--base-sub-text-color)]">周对比:</span>

              <el-tooltip
                class="box-item"
                effect="dark"
                content={`对比上周期销量：${row.week_ratio == "0" ? "持平" : row.week_ratio > 0 ? "上升" : "下降"} ${Math.abs(row.week_ratio)}`}
                placement="top-start"
              >
                <svg-icon
                  icon-class={row.week_ratio == 0 ? "trend_ping" : row.week_ratio > 0 ? "trend_up" : "trend_down"}
                  class="text-[18px] ml-[2px] cursor-pointer"
                  onClick={() => AsinSalesTrendRef.value.open("week", row)}
                />
              </el-tooltip>
            </div>

            <div class="flex items-center">
              <span class="text-[var(--base-sub-text-color)]">月对比:</span>

              <el-tooltip
                class="box-item"
                effect="dark"
                content={`对比上周期销量：${row.month_ratio == "0" ? "持平" : row.month_ratio > 0 ? "上升" : "下降"} ${Math.abs(row.month_ratio)}`}
                placement="top-start"
              >
                <svg-icon
                  icon-class={row.month_ratio == 0 ? "trend_ping" : row.month_ratio > 0 ? "trend_up" : "trend_down"}
                  class="text-[18px] ml-[2px] cursor-pointer"
                  onClick={() => AsinSalesTrendRef.value.open("month", row)}
                />
              </el-tooltip>
            </div>
          </div>
        ),
      },
    },

    {
      title: "平台信息",
      width: 200,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="售价" value={`${row.platform_price || "-"} ${row.currency}`} line={1} />
            <VText title="最低成交价" value={row.min_sales_price} line={1} class="text-red font-bold" />
            <VText title="平台类目" value={row.name} line={1} />
            <VText title="销售类型" value={row.name} line={1} />
            <VText title="类型" value={row.name} line={1} />
          </div>
        ),
      },
    },

    // {
    //   title: "系统可用库存",
    //   width: 110,
    //   slots: {
    //     default: ({ row }) => (
    //       <div>
    //         <VText value={row.inventory} line={1} type="link" onClick={() => AssembleSkuSeeRef.value.open(row)} />
    //       </div>
    //     ),
    //   },
    // },

    {
      title: "时间/日志",
      width: 240,
      field: "time",
      slots: {
        header: "soltHeader",
        default: ({ row }) => (
          <div>
            <VText title="创建时间" value={row.create_time} line={1} />
            <VText title="上架时间" value={row.platform_date} line={1} />
            <VText title="更新时间" value={row.update_time} line={1} />
            <VText title="首次到达FBA时间" value={row.receipt_goods_time} line={1} />
            <div class="flex items-center cursor-pointer text-[#3487ff]" onClick={() => logRef?.value.open({ business_id: row.id, tag: "goods" })}>
              <svg-icon icon-class="baobiao" class=" text-[18px] mr-[2px]" />
              日志
            </div>
          </div>
        ),
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        let params = { ...form, ...page }
        params = initForm(params)
        return queryList(params)
      },
    },
  },
})
const queryList = (params) => {
  return new Promise((resolve, reject) => {
    amazonListingList(params).then((res) => {
      res.data?.forEach((item) => {
        let name = item.operations_department?.split("/")
        name?.shift()
        name?.shift()
        item.operations_department = name?.join("/")
      })
      tableRef?.value?.$table.reloadData([])
      resolve(res)
    })
  })
}
const initForm = (params) => {
  let { isSort, skuRange, asinRange } = tableRef?.value.getForm()

  if (!isSort) {
    for (const key in headerMemu) {
      headerMemu[key].forEach((item) => {
        item.type = ""
      })
    }
    headerMemu.qty[2].type = "desc"
    isSort = true
  }
  if (isSort) {
    let sort = [...Object.values(headerMemu).flat(), ...Object.values(transitHeader).flat()]
    sort = sort.filter((v) => v.type).map((v) => ({ field: v.key, type: v.type }))
    params.sort = sort
  }
  params[skuRange.type] = skuRange?.value
    ?.split("\n")
    ?.filter((v) => !!v.trim())
    .map((v) => v.trim())

  params[asinRange.type] = asinRange?.value
    ?.split("\n")
    ?.filter((v) => !!v.trim())
    .map((v) => v.trim())

  params.sku_cn_title = params.sku_cn_title?.trim()
  params.platform_id = 2
  return params
}
</script>
<style lang="scss" scoped>
:deep(.view-table) {
  // .status-tag {
  //   width: 30px;
  //   height: 14px;
  //   line-height: 14px;
  //   text-align: center;
  //   border-radius: 2px;
  //   font-size: 10px;
  // }
  .bold-text {
    font-weight: bold;
    color: #3487ff;
    cursor: pointer;
  }
  .text-666 {
    * {
      // color: #666;
      color: var(--base-sub-text-color);
    }
  }
  .text-333 {
    * {
      // color: #333;
      color: var(--base-text-color);
    }
  }

  .zhandian-icon {
    width: 64px;
    height: 32px;
    margin-right: 8px;
    &.jp {
      border: 1px solid var(--base-text-color);
    }
  }
  .goods-tag {
    display: inline-block;
    background: #fafafa;
    border-radius: 4px;
    padding: 1px 6px;
    margin-top: 4px;
    border: 1px solid #cbcbcb;
  }
}

.day-table {
  border-top: 1px solid var(--base-link-color);
  border-left: 1px solid var(--base-border-color);
  * {
    line-height: 48px;
    text-align: center;
    border-bottom: 1px solid var(--base-link-color);
    border-right: 1px solid var(--base-link-color);
  }
  .header {
    background: var(--base-table-header-bg-color);
  }
  .value {
    color: #3487ff;
  }
}
</style>
